import { Form, Modal, Row, Col, Input, Select, Cascader, DatePicker, TreeSelect } from 'antd';
import dayjs from 'dayjs';
import { useEffect } from 'react';
import { connect } from 'umi';
import { getAllChildList, getAllParentList } from '@/utils/utils';

const DataForm = (props) => {
  const { dispatch, submitting, regionTree, userTagTree } = props;
  const { dataForm, setDataForm, tablePayload, setTablePayload } = props.data;
  const [form] = Form.useForm();

  /* 初始化表单数据 */
  useEffect(() => {
    if (dataForm && dataForm.data) {
      form.setFieldsValue({
        ...dataForm.data,
        birthday: dataForm.data.birthday ? dayjs(dataForm.data.birthday, 'YYYY-MM-DD') : undefined,
      });
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      if (values.tagIds) {
        values.tagIds = values.tagIds.map(d => d.value);
      }

      values.birthday = values.birthday ? dayjs(values.birthday).format('YYYY-MM-DD') : undefined;
      values.regionId = values.regionPath ? values.regionPath[values.regionPath.length - 1] : 0;
      dispatch({
        type: 'PVipUser/edit',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({ ...tablePayload });
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    form.resetFields();
  }

  function onTagChg(value, label, extra) {
    let tagIds;
    if (extra.checked) {  // 节点选中
      tagIds = value.map(d => d.value);
      tagIds = [...tagIds,
        ...getAllChildList(userTagTree, extra.triggerValue),
        ...getAllParentList(userTagTree, extra.triggerValue),
      ];
    } else {  // 节点取消选中
      tagIds = form.getFieldValue('tagIds') || [];
      tagIds = tagIds.map(d => d.value);
      let exclude = [extra.triggerValue, ...getAllChildList(userTagTree, extra.triggerValue)];
      tagIds = tagIds.filter(d => exclude.findIndex(id => id === d) < 0);
    }
    // 去重
    tagIds = [...new Set(tagIds)];
    // 赋值
    tagIds = tagIds.map(id => {
      let obj = { value: id };
      userTagTree.forEach(item => {
        if (id === item.id) {
          obj.label = item.name;
        }
      });
      return obj;
    });
    form.setFieldsValue({ tagIds });
  }

  return (
    <Modal
      confirmLoading={submitting}
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={900}
      bodyStyle={{ paddingTop: 24 }}
    >
      <Form layout="horizontal" labelCol={{ span: 5 }} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="mobile" label="手机号码"
              rules={[
                { required: true, message: '手机号码不能为空' },
              ]}>
              <Input placeholder="请输入手机号码" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="name" label="用户名称"
              rules={[
                { required: true, message: '用户名称不能为空' },
              ]}>
              <Input placeholder="请输入用户名称" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="gender" label="性别"
              rules={[
                { required: true, message: '性别不能为空' },
              ]}
            >
              <Select placeholder="请选择性别">
                <Select.Option value={0}>未知</Select.Option>
                <Select.Option value={1}>男</Select.Option>
                <Select.Option value={2}>女</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="tagIds" label="用户标签"
              rules={[
                { required: false, message: '用户标签不能为空' },
              ]}>
              <TreeSelect
                treeData={userTagTree}
                placeholder="请选择用户标签"
                treeCheckable={true}
                showCheckedStrategy={TreeSelect.SHOW_ALL}
                maxTagCount={2}
                treeCheckStrictly
                onChange={onTagChg}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="tel" label="电话"
              rules={[
                { required: false, message: '电话不能为空' },
              ]}>
              <Input placeholder="请输入电话" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="email" label="邮箱"
              rules={[
                { required: false, message: '邮箱不能为空' },
              ]}>
              <Input placeholder="请输入邮箱" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="idsn" label="身份证号"
              rules={[
                { required: false, message: '身份证号不能为空' },
              ]}>
              <Input placeholder="请输入身份证号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="birthday" label="生日"
              rules={[
                { required: false, message: '生日不能为空' },
              ]}>
              <DatePicker placeholder={'请选择生日'} style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="realName" label="真实姓名"
              rules={[
                { required: false, message: '真实姓名不能为空' },
              ]}>
              <Input placeholder="请输入真实姓名" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="regionPath" label="所属区县"
              rules={[
                { required: false, message: '所属区县不能为空' },
              ]}>
              <Cascader
                placeholder="请选择所属区县"
                options={regionTree}
                expandTrigger="hover"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="remark" label="备注信息"
              rules={[
                { required: false, message: '备注信息不能为空' },
              ]}>
              <Input.TextArea rows={3} placeholder="请输入备注信息" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};


export default connect(({ loading, SystemCommon, UserCommon }) => {
  return {
    submitting: loading.effects['PVipUser/edit'],
    regionTree: SystemCommon.regionTree,
    userTagTree: UserCommon.userTagTree,
  };
})(DataForm);

